<!--  -->
<template>
<div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb> 

    <!-- 卡片主体区 -->
    <el-card>
        <!-- 添加按钮区域 -->
         <el-row>
            <el-col>
                <el-button type="primary" @click="addrolesDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>

        <!-- 角色列表区域 -->
        <el-table :data="rolesList" border stripe>
            <el-table-column type="expand">
                <!-- scope.row 是每行的角色，scope.row.children是个数组，数组里放的对象，对应该角色下所有的权限，item1是个权限对象 -->
                <template slot-scope="scope"> 
                    <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']" 
                    v-for="(item1,i1) in scope.row.children" :key="item1.id">
                        
                        <!-- 一级权限 -->
                        <el-col :span="5">
                            <el-tag closable 
                                @close='removeRightById(scope.row,item1.id)'>
                                {{item1.authName}}
                            </el-tag> 
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        
                        <!-- 二级和三级 -->
                        <el-col :span="19">
                            <el-row :class="[i2 === 0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                <!-- 二级 -->
                                <el-col :span="6">
                                    <el-tag type="success" closable 
                                    @close='removeRightById(scope.row,item2.id)'>
                                        {{item2.authName}}
                                    </el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>

                                <!-- 三级 -->
                                <el-col :span="13">
                                    <el-tag closable 
                                    type="warning" 
                                    v-for="(item3) in item2.children" :key="item3.id"
                                    @close='removeRightById(scope.row,item3.id)'>
                                        {{item3.authName}}
                                    </el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>

           <el-table-column type="index">
            </el-table-column>

            <el-table-column label="角色名称" prop="roleName">
            </el-table-column>

            <el-table-column label="角色描述" prop="roleDesc">
            </el-table-column>

            <el-table-column label="操作" width="300px">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>

        </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
        title="添加角色"
        :visible.sync="addrolesDialogVisible"
        width="50%"
        @close='addrolesDialogClose'
        >
        <!-- 内容主体区 -->
        <el-form :model="addRolesForm" 
        :rules="addRolesFormRules"
        ref="addRolesFormRef" label-width="80px"
        >
            <el-form-item label="角色名" prop="roleName">
                <el-input v-model="addRolesForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRolesForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
         <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addrolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addroles">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
        title="分配权限"
        :visible.sync="SetRightDialogVisible"
        width="50%"
        @close='setRightDialogClose'
        >
        <!-- 内容主体区 树形控件-->
        <el-tree :data="rightsList" 
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys='defKeys'
        ref="treeRef">
        </el-tree>
         <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="SetRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotrights">确 定</el-button>
        </span>
    </el-dialog>

</div>
</template>

<script>
export default {
    data() {
        return {
            rolesList:[],
            // 添加角色用到的
            addrolesDialogVisible:false,
            addRolesForm:{
                roleName:'',
                roleDesc:''
            },
            addRolesFormRules:{
                roleName:[
                    { required: true, message: '请输入角色名', trigger: 'blur' }
                ],
                roleDesc:[
                    { required: true, message: '请输入角色描述', trigger: 'blur' }
                ]
            },
            // 权限分配用到的
            SetRightDialogVisible:false,
            rightsList:[],
            //树形控件绑定对象
            treeProps:{
                // 树形控件上显示的
                label:'authName',
                // 以什么作为树的分级
                children:'children'
            },
            // 树形控件默认选中的id值数组
            defKeys:[],
            roleID:''


        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        async getRolesList(){
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status !== 200){
                 return this.$message.error('获取角色列表失败')
            }
                 
            this.rolesList = res.data
        },
        addrolesDialogClose(){
            this.$refs.addRolesFormRef.resetFields()
        },

        addroles(){
            this.$refs.addRolesFormRef.validate(async valid => {
                if(!valid) return
                const{data:res} = await this.$http.post('roles',this.addRolesForm)
                if(res.meta.status != 201){
                    return this.$message.error('添加角色失败')
                }
                this.$message.success('添加角色成功')
                this.addrolesDialogVisible = false
                this.getRolesList()
            })   
        },
        //删除第三级权限
        async removeRightById(roleId,rightId){
            const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(e => e)
            if(result != 'confirm'){
                return this.$message.info('取消删除')
            }
            const {data:res} = await this.$http.delete(`roles/${roleId.id}/rights/${rightId}`)
            if(res.meta.status != 200){
                this.$message.error('删除失败')
            }
            // this.getRolesList()
            roleId.children = res.data
        },

        // 点击分配权限按钮的时候，展示分配权限的对话框
        async showSetRightDialog(role){
            //再打开分配权限框时，将该行的角色的ID存放到data中
            this.roleID = role.id
            const {data:res} = await this.$http.get('rights/tree')
            if(res.meta.status != 200){
                this.$message.error('获取权限数据失败')
            }
            this.rightsList = res.data
            this.getLeafKeys(role, this.defKeys)
            this.SetRightDialogVisible = true
        },

        // 通过递归的形式，获取所有角色下三级权限的id
        // 并保存到defKeys中
        getLeafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(item =>{
                this.getLeafKeys(item,arr)
            })
        },
        //监听对话框的关闭事件，这个事件使defKeys数组重置
        setRightDialogClose(){
            this.defKeys = []
        },
        // 在打开分配权限对话框后，按下确定，数据保存到后端
        async allotrights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idstr = keys.join(',')
            const {data:res} = await this.$http.post(`roles/${this.roleID}/rights`,{rids:idstr})
            if(res.meta.status != 200){
                return this.$message.error('分配权限失败')
            }
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.SetRightDialogVisible = false

        }

        
    }
}
</script>

<style lang='less' scoped>
.el-tag{
    margin: 7px;
}

.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>